package com.project.personal_blog.garbage_classification_management_system.Controller;

import com.project.personal_blog.garbage_classification_management_system.pojo.Code;
import com.project.personal_blog.garbage_classification_management_system.pojo.Result;
import com.project.personal_blog.garbage_classification_management_system.pojo.User;
import com.project.personal_blog.garbage_classification_management_system.service.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class RegisterController {
    @Autowired
    private RegisterService registerService;

    @PostMapping("/register")
    public ResponseEntity<Result> register(@RequestBody User user) {
        // 检查密码长度
        if (user.getPassword().length() < 8 || user.getPassword().length() > 16) {
            Result result = new Result("fail", Code.PASSWORD_LENGTH_ERROR, "密码长度必须在8到16位之间");
            return ResponseEntity.badRequest().body(result);
        }
        // 检查密码格式
        if (!user.getPassword().matches("^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[!@#$%^&*]).{8,16}$")) {
            Result result = new Result("fail", Code.PASSWORD_FORMAT_ERROR, "密码必须包含字母、数字和符号");
            return ResponseEntity.badRequest().body(result);
        }
        // 注册用户
        User registeredUser = (User) registerService.register(user.getUsername(), user.getPassword(), user.getEmail(), user.getPhoneNumber());
        if (registeredUser != null) {
            Result result = new Result("secures", Code.REGISTER_SUCCESS, registeredUser.getGtId());
            return ResponseEntity.ok(result);
        } else {
            Result result = new Result("fail", Code.REGISTER_FAIL, "注册失败");
            return ResponseEntity.ok(result);
        }
    }
}
